package ink.tiptop.common.worker.install;


import ink.tiptop.constant.Cmd;
import ink.tiptop.utils.async.callback.ICallback;
import ink.tiptop.utils.async.callback.IWorker;
import ink.tiptop.utils.async.worker.WorkResult;
import ink.tiptop.utils.async.wrapper.WorkerWrapper;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Map;

/**
 * @author wuweifeng wrote on 2019-11-20.
 */
@Slf4j
public class InstallWorker implements IWorker<List<InstallParam>, InstallResult>, ICallback<List<InstallParam>, InstallResult> {

    /**
     * mavenhome
     */
    private String mavenHome;
    /**
     * 所属项目的idea右上角配置文件选项
     */
    private String profile;

    public InstallWorker(String mavenHome,String profile) {
        this.mavenHome = mavenHome;
        this.profile = profile;
    }

    @Override
    public void begin() {
        log.info("开始执行install操作");
    }

    @Override
    public void result(boolean success, List<InstallParam> param, WorkResult<InstallResult> workResult) {
        log.info("完成install操作");
    }

    @Override
    public InstallResult action(List<InstallParam> params, Map<String, WorkerWrapper> allWrappers) {
        InstallResult result = new InstallResult();
        for (InstallParam p : params) {
            File jarFile = new File(p.getJar());
            if (jarFile.exists()) {
                jarFile.delete();
            }
            Process process = null;//通过cmd程序执行cmd命令
            try {
                // 这个第三个参数file是执行的路径
                String pomParent = p.getParent() + File.separator + p.getName();
                String installCmd = String.format(Cmd.INSTALL, pomParent, mavenHome, mavenHome, mavenHome, profile);
                Runtime runtime = Runtime.getRuntime();
                process = runtime.exec(installCmd, null, new File(pomParent));
                //读取屏幕输出
                BufferedReader strCon = new BufferedReader(new InputStreamReader(process.getInputStream()));
                String line;
                while ((line = strCon.readLine()) != null) {
                    log.info(line);
                }
                result.addSuccess(p.getJar());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                // 添加到部分成功里面
                result.addFailed(p.getJar());
            }
        }
        if (!result.getFailedList().isEmpty()) {
            result.setStatus(InstallStatus.PART_SUCCESS);
        } else {
            result.setStatus(InstallStatus.SUCCESS);
        }
        return result;
    }

    @Override
    public InstallResult defaultValue() {
        return new InstallResult(InstallStatus.FAILED);
    }
}
